package cn.ham.service.impl;

import cn.ham.dao.ProjectDao;
import cn.ham.entity.Project;
import cn.ham.entity.RestApi;
import cn.ham.file.handle.ClassParse;
import cn.ham.service.ProjectService;
import cn.ham.service.RestApiService;
import cn.ham.utils.ShellUtil;
import cn.ham.utils.SystemProperties;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @author 18号
 * @date 2016/11/26 18:37
 */
@Service
public class ProjectServiceImpl implements ProjectService{
    private static Logger logger = LoggerFactory.getLogger(ProjectServiceImpl.class);
    @Autowired
    private RestApiService restApiService;

    @Autowired
    private ProjectDao projectDao;
    @Autowired
    private SystemProperties systemProperties;


    @Transactional
    @Override
    public void build(Project project) {
        String relyUrl = project.getRelyUrl();
        String[] gitUrl = relyUrl.split(";");
        String[] classLoader = new String[gitUrl.length];
        for (int i=0;i<gitUrl.length;i++){
            String proName = gitUrl[i].substring(gitUrl[i].lastIndexOf("/")+1,gitUrl[i].lastIndexOf("."));
            String proDir = systemProperties.getProdir()+proName;
            // clone project
            String git = "git clone "+gitUrl[i]+" "+proDir;
            ShellUtil.shellTask(git);
            // mvn compile project
            String mvn = "cd "+proDir+" &&mvn compile";
            ShellUtil.shellTask(mvn);
            classLoader[i] = "file:"+proDir+systemProperties.getClassroot();
            logger.info("git is:{},mvn is:{},proName is:{},proDir is:{},classLoader is:{}",new Object[]{git,mvn,proName,proDir,classLoader[i]});
        }

        String apiProName = project.getApiUrl().substring(project.getApiUrl().lastIndexOf("/"),project.getApiUrl().lastIndexOf("."));
        String apiProDir = systemProperties.getProdir()+apiProName;
        // clone project
        String git = "git clone "+project.getApiUrl()+" "+apiProDir;
        ShellUtil.shellTask(git);
        // mvn compile project
        String mvn = "cd "+apiProDir+" &&mvn compile";
        ShellUtil.shellTask(mvn);
        logger.info("git is:{},mvn is:{},apiProName is:{},apiProDir is:{},api url is:{}",new Object[]{git,mvn,apiProName,apiProDir,apiProDir});
        // 保存工程信息
        int id = projectDao.save(project);

        // 获取api url
        List<RestApi> restApis = ClassParse.parse(apiProDir+systemProperties.getClassroot(),classLoader,id);
        restApiService.add(restApis);
    }

    @Override
    public List<Project> getAll() {
        return projectDao.selectAll();
    }

    @Override
    public Project getById(int proId) {
        return projectDao.selectById(proId);
    }
}
